import {DIC_PROPS, TAG_DIC} from "components/avue/global/variable";

const tagTools = {}
const tagDicProps = {
    type: "tagType",
    hit: "tagHit",
    color: "tagColor",
    size: "tagSize",
    effect: "tagEffect",
    round: "tagRound"
}


function handlerTagPropMap(column, val, row) {

    if (!column.tag) {
        return null;
    }
    let tagPropMap = column.tagProp
    if (!tagPropMap) {
        return null
    }
    if (tagPropMap instanceof Function) {
        return tagPropMap(val, row, column)
    }
    let result = tagPropMap[val]
    if (!result) {
        return null;
    }
    if (typeof result !== 'object') {
        return null;
    }
    return result;
}

function handlerDicMap(column, dic, value) {
    if (!TAG_DIC.includes(column.type)) {
        return {}
    }
    if (!dic) {
        return null
    }
    if (!Array.isArray(dic)) {
        return null;
    }
    let colProps = column.props || {};
    let valueKey = colProps.value || DIC_PROPS.value
    let dicItem = dic.find(e => e[valueKey] === value)
    if (!dicItem || !dicItem.tag || !dicItem.tagProp) {
        return null;
    }

    let tagProp = dicItem.tagProp;
    if (typeof tagProp !== 'object') {
        return null;
    }
    let has = false;
    let result = {};
    for (const tagDicPropsKey in tagDicProps) {
        let key = tagDicProps[tagDicPropsKey];
        if (!tagProp[key]) {
            continue;
        }
        result[key] = tagProp[key];
        has = true;
    }
    return has ? result : null;
}

export function getTagProp(column, val, dic, row) {
    if (!column.tag) {
        return null;
    }
    let result;
    if (dic) {
        result = handlerDicMap(column, dic, val)
    }
    if (result) {
        return result;
    }

    result = handlerTagPropMap(column, val, row)
    return result || {}
}

tagTools.getTagProp = getTagProp
tagTools.tagDicProps = tagDicProps

export default tagTools
